package player

import (
	"GameServer/Common/data"
	"GameServer/Common/utils"
	"GameServer/Game/activity"
	"GameServer/Game/errors"
	"GameServer/Game/lib"
	"GameServer/Game/m"
	"GameServer/Game/sp"
)

// 老虎机行为触发 (data.SlotActActionEnum行为枚举, spin当前押注)
func (p *Player) SlotActActionOccur(actionEnum int64, spin int64) {
	// if p.User.MaxPos.LockBlockTid < 2 {
	// 	return
	// }

	// ---Func
	TryActLevelUp := func(u *m.User, actId int64, addItemNum int64) {
		if addItemNum == 0 { // 增量为0，不做处理
			return
		}
		uProp, _, rewards, err := lib.TryActProgressLevelUp("SlotActActionOccur", u, actId, addItemNum, p.Send)
		if uProp != nil {
			request := new(sp.SingleActivityPushProgressRequest)
			p.TimelyUpdateProp(request.GetType(), uProp)
			utils.AsyncFunc(func() {
				p.UpdateProp(request.GetType(), uProp)
			})
		}
		if err == nil {
			p.PushSingleActProgress(actId, rewards)
		}
		return
	}
	// ---
	slotActMap := activity.ActivityModule.GetActActivityByType(data.ActivityEnum.Slot)
	if slotActMap != nil {
		for _, act := range slotActMap { //遍历所有激活的老虎机活动
			actId := act.ActId
			actInTime := lib.IsActActivityInActTime(act) //检查是否在激活时间内
			if actInTime {
				actConfig, err := lib.GetSlotActConfigeTableInfo(act.ActId) //获得配表
				var addNum int64 = 0
				if err == nil {
					switch actionEnum {
					case data.SlotActActionEnum.TrebleSp:
						//获得三个活动道具
						addNum = ((int64(actConfig.TigerGain)) * spin)
					case data.SlotActActionEnum.Stole:
						//偷盗
						addNum = ((int64(actConfig.StoleGain)) * spin)
					case data.SlotActActionEnum.SucAtt:
						//攻击成功
						addNum = ((int64(actConfig.SucAttGain)) * spin)
					case data.SlotActActionEnum.FailAtt:
						//攻击失败
						addNum = ((int64(actConfig.FailAttGain)) * spin)
					default:
						//缺省未知行为
						addNum = 0
					}
					TryActLevelUp(p.User, actId, addNum)
				}
			}
		}
		return
	}
	return
}

// 活动详情内容推送 s-c 15005
func (p *Player) PushAllActActivityInfo() {
	// 进度获取
	userProgress := p.User.GetUserActProgress() // 获取缓存中的所有进度，并检测有效性，此时会清理掉过期的活动进度
	actList, _ := lib.GetActActivityList()      // 重新读表，获取激活的活动列表
	if actList != nil && len(actList) > 0 {
		for _, act := range actList {
			_, _ = lib.GetOrCreateActProgress(p.User, int64(act.ActivId)) // 根据激活的活动列表，获取/初始化活动进度
		}
	}
	deleteList := []int64{}
	for _, progress := range userProgress.ActProgressList {
		var findAct bool = false
		for _, act := range actList {
			if progress.ActId == int64(act.ActivId) {
				findAct = true
			}
		}
		if findAct == false {
			deleteList = append(deleteList, progress.ActId)
		}
	}
	if len(deleteList) > 0 {
		for _, Value := range deleteList {
			userProgress.DeleteProgress(Value)
		}
	}
	userProgress = p.User.GetUserActProgress() // 重新获取，缓存中的，所有进度
	// 活动获取
	activityAll := lib.FormatTotalActActivity(activity.ActivityModule.GetAndCheckActActivityList())

	// 加载委托活动
	if entrActiv, err := lib.GetCurrentEntrustActiv(); err == nil {
		activityAll = append(activityAll, lib.FormatEntrActiv(&entrActiv))
	}
	pushRes := &sp.ActivityPushTotalWithProgressRequest{
		ActivityAll:     activityAll,
		UserProgressArr: lib.FormatUserActProgressList(userProgress.ActProgressList),
	}
	p.Send(pushRes)
}

//获取所有活动进度 15001
func (p *Player) GetUserActProgressRequest(req *sp.GetUserActProgressRequest) (res *sp.GetUserActProgressResponse) {
	// 玩家没有达到1-2关，不能获取活动信息
	if p.User.MaxPos.LayerId >= 2 {
		res = &sp.GetUserActProgressResponse{}
		return
	}
	userProgress := p.User.GetUserActProgress() // 获取缓存中的所有进度，并检测有效性，此时会清理掉过期的活动进度
	actList, _ := lib.GetActActivityList()      // 重新读表，获取激活的活动列表
	if actList != nil && len(actList) > 0 {
		for _, act := range actList {
			_, _ = lib.GetOrCreateActProgress(p.User, int64(act.ActivId)) // 根据激活的活动列表，获取/初始化活动进度
		}
	}
	deleteList := []int64{}
	for _, progress := range userProgress.ActProgressList {
		var findAct bool = false
		for _, act := range actList {
			if progress.ActId == int64(act.ActivId) {
				findAct = true
			}
		}
		if findAct == false {
			deleteList = append(deleteList, progress.ActId)
		}
	}
	if len(deleteList) > 0 {
		for _, Value := range deleteList {
			userProgress.DeleteProgress(Value)
		}
	}
	userProgress = p.User.GetUserActProgress() // 重新获取，缓存中的，所有进度

	res = &sp.GetUserActProgressResponse{
		UserProgressArr: lib.FormatUserActProgressList(userProgress.ActProgressList),
	}
	return
}

// 单个活动进度推送 s-c 15002
func (p *Player) PushSingleActProgress(actId int64, rewards []*sp.ActivityReward) {
	userProgress := p.User.GetUserActProgress()
	singleActProgress, findProgress := userProgress.GetActivityProgress(actId)
	if findProgress {
		p.Send(&sp.SingleActivityPushProgressRequest{
			ActId: actId,
			UserProgress: &sp.UserActivityProgress{
				ActivID:           singleActProgress.ActId,
				CurRound:          singleActProgress.CurRound,
				CurRoundItemCount: singleActProgress.CurRoundItemCount,
				TotalItemCount:    singleActProgress.TotalItemCount,
				GainRoundReward:   singleActProgress.GainRoundReward,
				RankId:            singleActProgress.RankId,
			},
			Rewards: rewards,
		})
	} else {
		// 找不到活动进度，可能活动已经失效，这个时候可以不psuh
	}
}

// 主动申请获得活动奖励 15003 (客户端判断，主动告知服务器进度完成)
func (p *Player) GetActivityRewardRequest(req *sp.GetActivityRewardRequest) (res *sp.GetActivityRewardResponse) {
	actId := req.ActivID
	// 活动失效检测
	inTime := lib.IsActActivityInActTimeByActId(actId)
	if inTime == false {
		err := errors.NewErrcode(data.Errcode.NotFound, "没找到该活动，或已超时")
		res = &sp.GetActivityRewardResponse{
			Errcode: errors.ErrCode(err),
		}
		return
	}
	//通知进度的数据层，修改当前进度
	uProp, progress, rewards, err := lib.TryActProgressLevelUp("GetActivityRewardRequest", p.User, actId, 1, p.Send) // 注意，本方法默认增量为1
	if err != nil {
		res = &sp.GetActivityRewardResponse{
			Errcode: errors.ErrCode(err),
		}
		return
	}
	//获取奖励并发放
	res = &sp.GetActivityRewardResponse{
		Errcode: 0,
		ActivID: actId,
		UserProgress: &sp.UserActivityProgress{
			ActivID:           progress.ActId,
			CurRound:          progress.CurRound,
			CurRoundItemCount: progress.CurRoundItemCount,
			TotalItemCount:    progress.TotalItemCount,
			GainRoundReward:   progress.GainRoundReward,
			Close:             progress.Close,
		},
		Rewards: rewards,
	}
	if uProp != nil {
		p.TimelyUpdateProp(req.GetType(), uProp)
		utils.AsyncFunc(func() {
			p.UpdateProp(req.GetType(), uProp)
		})
	}
	return
}
